class Cart {
    constructor() {
        this.axiosRes();
        this.checkLogin();
        this.addCart();
        this.bindEve();
    }
    // 绑定事件的方法
    bindEve() {
        // 全选
        this.$('#checkAll').addEventListener('click', this.checkAll.bind(this));
        // 单选，给商品共同父级绑定点击事件
        this.$('#listing').addEventListener('click', this.dispatch.bind(this));
        this.$('#listing').addEventListener('input', this.changeNum.bind(this));
    }

    // axios响应拦截
    axiosRes() {
        // 添加响应拦截器
        axios.interceptors.response.use(function (response) {
            // 对响应数据做点什么
            // console.log(response);
            if (response.data.code == 401) {
                location.assign('./login.html?returnUrl=./cart.html');
            }
            return response;
        }, function (error) {
            // 对响应错误做点什么
            return Promise.reject(error);
        });
    }

    // 验证登录
    checkLogin() {
        const TOKEN = localStorage.getItem('token');
        if (!TOKEN) location.assign('./login.html?returnUrl=./cart.html')
    }

    // ajax 渲染数据
    async addCart() {
        let userId = localStorage.getItem('user_id')

        let token = localStorage.getItem('token');

        // 设置编码方式
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

        // 设置请求头
        axios.defaults.headers.common['Authorization'] = token;
        // 发送ajax , 加入购物车
        let { status, data } = await axios.get('http://localhost:8888/cart/list?id=' + userId);
        // console.log(status, data);
        // console.log(data.cart);
        // 判断服务器状态
        if (status != 200) return;
        if (data.code == 0) location.assign('./login.html?returnUrl=./cart.html');
        localStorage.setItem('cart', data.cart.length)
        if (data.code == 1) {
            // 渲染购物车数据
            let html = '';
            data.cart.forEach(goods => {
                html += `<ul class="tro_tab_h1" data-id="${goods.goods_id}">
                <div class="col tro_tab_check">
                <h1 class="tro_tab_check_p">
                    <input type="checkbox" name="" class="pitchUp" id="" value="">
                </h1>
                <span class="tro_tab_check_sp"></span>

            </div>
            <div class="col tro_tab_img">
                <img src="${goods.img_small_logo}" alt="">

            </div>
            <div class="col tro_tab_name">
                <li class="tro_tab_name_li1">${goods.title}</li>
                <li class="tro_tab_name_li2">适配类型:${goods.category}</li>

            </div>
            <div class="col tro_tab_price">
                <span class="univalence" id="">${goods.current_price}</span><span>元</span>
            </div>
            <div class="col tro_tab_num">
                <a class="tro_tab_num_p1" id="" href="javascript:;">-</a>
                <input type="text" value="${goods.cart_number}" id="" class="num">
                <a class="tro_tab_num_p2" id="" href="javascript:;">+</a>
            </div>
            <div class="col tro_tab_total "><span class="tro_tab_total_value" id="">${(goods.current_price * goods.cart_number).toFixed(2)}</span>元

            </div>
            <div class="col tro_tab_action">x</div>
            </ul>`
            })

            // 追加到页面中去
            this.$('#listing').innerHTML = html;
            // this.total();
            // this.$('#checkAll').addEventListener('click', this.checkAll.bind(this));
        }

        // console.log(res);
    }

    // 全选
    checkAll(eve) {
        // 获取全选的状态
        let status = eve.target.checked
        // console.log(status);
        this.setOneCheck(status);
        this.total();
    }

    // 单个框的状态
    setOneCheck(status) {
        let oneGoods = document.querySelectorAll('.pitchUp')
        // console.log(pitchUp);
        oneGoods.forEach(ele => {
            ele.checked = status;
        })
    }

    // 判断点击的是谁
    dispatch(eve) {
        let tar = eve.target;
        // 单选
        if (tar.classList.contains('pitchUp')) {
            this.manageOneG(tar);
            this.total();
        }
        // 删除
        if (tar.classList.contains('tro_tab_action')) {
            this.delGoods(tar);
        }

        // 增加或减少
        if (tar.classList.contains('tro_tab_num_p2') || tar.classList.contains('tro_tab_num_p1')) {
            this.changeNum(eve);
        }

    }

    // 单个商品点击状态
    manageOneG(tar) {
        // console.log(tar, tar.checked); 
        if (tar.checked) {
            // 判断页面中所有的商品状态
            let oneGoods = document.querySelectorAll('.pitchUp');
            ![...oneGoods].some(ele => !ele.checked) && (this.$('#checkAll').checked = true);
        } else {
            this.$('#checkAll').checked = false;
        }
    }

    // 修改数量的方法
    changeNum(eve) {
        // console.log(eve.target);
        if (eve.target.classList.contains('pitchUp')) {
            return;
        }
        // console.log(eve.type);
        let input = '';
        let val = 0;
        // 判断操作类型
        if (eve.type == 'click') {
            // console.log(111);
            // 判断加减
            // 加
            let mark = eve.target.innerHTML

            if (mark == '+') {
                input = eve.target.previousElementSibling
                val = input.value - 0 + 1;
            }
            // 减
            if (mark == '-') {
                input = eve.target.nextElementSibling
                val = input.value - 1;
                if (val < 1) val = 1;
            }
            input.value = val;
        }

        // 输入事件
        if (eve.type == 'input') {
            // console.log(222);
            input = eve.target
            val = input.value;
            // console.log(val);
            let reg = /^[\d]+$/;
            if (!reg.test(input.value)) {
                layer.msg(
                    '输入错误',
                    { icon: 5, shade: [0.8, '#393D49'], time: 1500 },
                    function () {
                        location.reload();
                    }
                )
            }

        }

        this.sumPrice(val, eve.target)
    }

    // 小计的实现
    sumPrice(num, target) {
        let ul = this.deep(target)
        // console.log(ul, num);

        // 获取单价
        let price = this.getChildren(ul, '.univalence', 'innerHTML')
        // console.log(price);
        let sum = ul.querySelector('.tro_tab_total_value')

        sum.innerHTML = (num * price).toFixed(2);

        // 发送ajax，修改服务器数量
        let goodsId = ul.dataset.id;
        this.sendAjaxNum(goodsId, num);

        // 计算总价
        this.total()

    }
    times = '';// 防抖
    // 修改服务器数量
    sendAjaxNum(goodsId, num) {
        // 延时器防抖
        clearTimeout(this.times);
        this.times = setTimeout(() => {
            let userId = localStorage.getItem('user_id');

            let token = localStorage.getItem('token');

            // 设置编码方式
            axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

            // 设置请求头
            axios.defaults.headers.common['Authorization'] = token;

            let param = `id=${userId}&goodsId=${goodsId}&number=${num}`
            axios.post('http://localhost:8888/cart/number', param).then(({ status, data }) => {
                // console.log(data);
                if (data.code == 0) {
                    layer.msg(
                        '库存不够了',
                        { icon: 5, shade: [0.8, '#393D49'], time: 1500 },
                        function () {
                            location.reload();
                        }
                    )
                }

            })
        }, 300)

    }

    // 删除的实现
    delGoods(tar) {
        let redDel = this.deep(tar);
        // console.log(redDel);
        let that = this;
        // console.log(redDel);
        layer.msg('是否删除', {
            time: 20000, //20s后自动关闭
            btn: ['是', '否'],
            yes(index) {
                layer.close(index);
                // console.log(111);
                let userId = localStorage.getItem('user_id');
                let goodsId = redDel.dataset.id;
                let token = localStorage.getItem('token');

                // axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

                // 设置请求头
                axios.defaults.headers.common['Authorization'] = token;
                // 发送ajax , 加入购物车
                axios.get('http://localhost:8888/cart/remove?id=' + userId + '&goodsId=' + goodsId).then(({ status, data }) => {
                    // console.log(status, data);
                    // 判断服务器状态和借口状态
                    if (status == 200 && data.code == 1) {
                        // 删除ul
                        redDel.remove()

                        // 获取当前商品是否选中
                        that.getChildren(redDel, '.pitchUp', 'checked') && that.total();


                    }
                });

            }
        });
    }

    // 获取总数计算总价
    total() {
        // console.log(rar);
        let troTab = document.querySelectorAll('.tro_tab_h1')
        // console.log(troTab);
        let tNum = 0;
        let tSubtotal = 0;

        troTab.forEach(ul => {
            let checkbox = this.getChildren(ul, '.pitchUp', 'checked');
            if (checkbox) {
                let num = this.getChildren(ul, '.num') - 0;
                let subtotal = this.getChildren(ul, '.tro_tab_total_value', 'innerHTML') - 0;
                // console.log(checkbox, num, subtotal);
                tNum += num;
                tSubtotal += subtotal;
            }
            // console.log(checkbox, num, subtotal);
        })
        // console.log(tNum, tSubtotal);

        // 追加到页面中去
        this.$('.trolley_background_in .tro_close_bot').innerHTML = `<a href="./list.html">
            <p class="tro_close_p ">继续购物 | 已选择了<span>${tNum}</span>件<span
                style="color: #ff6700"></span>
            </p>
        </a>
        <a href="./success.html"><p class="tro_close_p_r">去结算</p></a>
        <p class="tro_close_p_c">合计:<span id="close">${tSubtotal.toFixed(2)}</span>元</p>`;
    }

    // 递归寻找父级
    deep(ele, tar = 'ul') {
        if (ele.nodeName == tar.toUpperCase()) {
            return ele;
        }
        return this.deep(ele.parentNode)
    }

    // 获取父节点下子节点的方法
    getChildren(father, children, attr = 'value') {
        return father.querySelector(children)[attr];
    }

    // 获取节点的方法
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res;
    }
}

new Cart;